using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class Box : MonoBehaviour
{
    /**爆开特效 */
    public GameObject burstEffect;

    /**武器 */
    public GameObject weapon;
    
    /**武器图片集合 */
    public Sprite[] weaponImgs;
    
    /**武器类型 */
    public GameWeapon weaponType = GameWeapon.Null;

    private SpriteRenderer _spriteRenderer;
    private BoxCollider2D _boxCollider2D;
    private Animator _animator;

    // Start is called before the first frame update
    void Start()
    {
        _spriteRenderer = GetComponent<SpriteRenderer>();
        _boxCollider2D = GetComponent<BoxCollider2D>();
        _animator = GetComponent<Animator>();

        if (weaponType == GameWeapon.Null)
        {
            weaponType = (GameWeapon) Random.Range(0, weaponImgs.Length);
        }
        weapon.GetComponent<SpriteRenderer>().sprite = weaponImgs[(int) weaponType];
    }

    private void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("Player"))
        {
            _animator.SetTrigger("hit");
            Invoke(nameof(Hit), 0.2f);
        }
    }

    /**碰撞 */
    private void Hit()
    {
        if (!_boxCollider2D.enabled)
        {
            return;
        }
        _spriteRenderer.enabled = false;
        _boxCollider2D.enabled = false;
        
        burstEffect.SetActive(true);
        weapon.SetActive(true);
        
        Invoke(nameof(EffectEnd), 0.2f);
    }

    /**效果结束 */
    private void EffectEnd()
    {
        burstEffect.SetActive(false);
        
        // 等待 0.5s 后消失，添加武器
        Invoke(nameof(AddWeapon), 0.5f);
    }

    /**添加武器 */
    private void AddWeapon()
    {
        WeaponMgr.instance.AddWeapon(weaponType);
        Destroy(transform.parent.gameObject, 0.5f);
    }
}
